import type { TreeOptionProps } from "element-plus/es/components/tree/src/tree.type.mjs";
import { useMessage } from "@/hooks/message";
import { onMounted } from "vue";

/**
 * 分页属性配置接口
 */
export declare interface BasicTreeProps {
  // 当前页码，默认为1
  label?: string;
  // 每页显示条数，默认为10
  children?: string;
  // 总条数，默认为0
  disabled?: string;
  // 每页显示条数选择器的选项数组，默认为[10,20,30,40]
  isLeaf?: string;
  // 分页组件布局方式，可选值有 total,sizes,prev,jump,next，默认为'total,sizes,prev,jump,next'
  class?: string;
}

/**
 * 表格组件基础配置属性
 */
export declare interface BasicTree {
  // 是否在创建页面时即调用数据列表接口，默认为true
  autoLoad?: boolean;
  // 查询条件表单对象，类型为any
  queryForm?: any;
  // 数据列表数组
  dataList?: Array<any>;
  // 数据列表查询接口api方法，接收任意数量参数，返回Promise
  queryFunction?: (...arg: any) => Promise<any>;
  loading?: boolean;
  // 排序字段数组
  descs?: string[];
  // 排序方式数组
  ascs?: string[];
  // props属性对象，类型为any
  props?: TreeOptionProps;
  //节点数据属性，类型为any
  dataProps?: any;
  // 回调事件，类型为any
  onLoaded?: (dataList?: any[]) => void;
}

const initQueryForm = {};

export function useTree(options?: BasicTree) {
  const defaultOptions: BasicTree = {
    // 是否需要自动请求创建接口来获取表格数据，默认为true
    autoLoad: true,
    loading: false,
    // 查询表单对象，用于提交条件查询时的参数传递，默认为空对象
    queryForm: {},
    // 表格展示的数据数组，默认为空数组
    dataList: [],
    // 分页组件属性配置，如当前页码、每页展示数据条数等，默认值为 {current:1, size:10,total:0,pageSizes:[1, 10, 20, 50, 100, 200],layout:'total, sizes, prev, pager, next, jumper'}
    props: {
      label: "label",
      children: "children",
      disabled: "disabled",
      isLeaf: "leaf",
      class: ""
    } as unknown as TreeOptionProps,
    dataProps: {
      pid: "pid"
    },
    // 排序时使用的字段名数组，如 ['id','name']，默认为空数组
    descs: [],
    // 排序方向数组，如 ['asc', 'desc']，默认为空数组
    ascs: []
  };

  /**
   * 合并默认属性配置和自定义属性配置
   * @param options 默认属性配置对象
   * @param props 自定义属性配置对象
   * @returns 合并后的属性配置对象
   */
  const mergeDefaultOptions = (defaultOptions: any, options: any): BasicTree => {
    for (const key in defaultOptions) {
      if (!Object.getOwnPropertyDescriptor(options, key)) {
        options[key] = defaultOptions[key];
      }
    }
    for (const key in options.queryForm) {
      initQueryForm[key] = options.queryForm[key];
    }
    return options;
  };

  // 覆盖默认值
  const instance = mergeDefaultOptions(defaultOptions, options);

  /**
   * 发起分页查询，并设置表格数据和分页信息
   */
  const query = async () => {
    // 判断是否存在instance.queryFunction属性
    if (instance.queryFunction && !instance.loading) {
      instance.loading = true;
      // 调用instance.queryFunction方法发起查询
      await instance
        .queryFunction({
          ...instance.queryForm,
          descs: instance.descs.join(","),
          ascs: instance.ascs.join(",")
        })
        .then(res => {
          if (res.code === 200) {
            // 设置表格展示的数据数组
            instance.dataList = res.data;
            // 执行回调事件
            if (instance.onLoaded) instance.onLoaded(instance.dataList);
          } else {
            useMessage().error(res.msg);
          }
          instance.loading = false;
        })
        .catch(() => {
          instance.loading = false;
        });
    }
  };

  /**
   * 获取数据列表，并可选择是否刷新当前页码
   * 刷新后不跳转第一页，则入参 getDataList(false)
   * @param refresh 是否刷新当前页码
   */
  const queryTreeData = (params?: any, paramsOverride: boolean = false) => {
    // 再次发起查询操作
    if (params) {
      for (const key in params) {
        instance.queryForm[key] = params[key];
        if (paramsOverride) {
          initQueryForm[key] = params[key];
        }
      }
    } else {
      instance.queryForm = {};
      for (const key in initQueryForm) {
        instance.queryForm[key] = initQueryForm[key];
      }
    }
    instance.loading = false;
    query();
  };

  const filterNode = params => {
    queryTreeData(params);
  };

  const lazyLoadNode = (node: any, resolve) => {
    setTimeout(async () => {
      if (node.data.id) {
        const params = {};
        params[instance.dataProps.pid] = node.data.id;
        params["ascs"] = instance.ascs.join(",");
        params["descs"] = instance.descs.join(",");
        await instance.queryFunction(params).then(res => {
          if (res.code === 200) {
            if (res.data) {
              resolve(res.data);
            }
          } else {
            resolve();
          }
        });
      }
    }, 500);
  };

  const handleResetQuery = () => {
    for (const key in initQueryForm) {
      instance.queryForm[key] = initQueryForm[key];
    }
    query();
  };

  const handleReset = () => {
    instance.dataList = [];
    for (const key in initQueryForm) {
      instance.queryForm[key] = initQueryForm[key];
    }
  };

  onMounted(() => {
    if (instance.autoLoad) {
      query();
    }
  });

  return {
    instance,
    queryTreeData,
    handleResetQuery,
    lazyLoadNode,
    handleReset,
    filterNode
  };
}
